home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: start array at k, not 0
- Date: 5 Jan 1996 17:14:15 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4cjm97$i5s@news.iag.net>
- References: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: pm3-orl15.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>,
- wsimpson@uwinnipeg.ca says...
- >
- >I have come up with the following 2 methods that allow one to talk about
- >an array that starts at element k rather than 0. E.g. 10 element array
- >y[k] to y[k+10]. Both seem to work. Is this illusory? Is one of the
-
- y[k+10] would be the 11th element of your 10 element array.
-
- >2 ways better (or a way I haven't mentioned)?
- >
- >These programs set up y[5] to y[14].
-
- >/*method 1*/
- >#include <stdio.h>
- >
- >int main(void)
- > {
- > int i, x[10];
- > int* y;
- > int offset=5; /*ie 1st index at 5, y[5]-y[14] */
- > y=x-offset;
- <snip>
-
- The c.l.c faq (Frequently Asked Question) list explains this one in Q6.17.
- Basically: "pointer arithmetic is defined only as long as the pointer points
- within the same allocated block of memory, or to the imaginary "terminating"
- element one past it" The faq list is available for anonymous ftp from
- rtfm.mit.edu /pub/usenet/comp.lang.c.
-
- >int main(void)
- > {
- > int i;
- > int* y;
- > int offset=5;
- > int n=10;
- > y=malloc(n*sizeof(int));
- >
- > printf("offset=%d\n",offset);
- >
- > for (i=offset;i<n+offset;i++)
- > {
- > y[i]=i;
-
- You allocated an array of 10 ints. The array starts at y[0] and ends at y[9].
- This loop is attempting to access y[5] through y[14]. So, 6 of your accesses
- are illegal (y[10] through y[14]).
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-